/**
 * 
 */
package org.rk.core.auth.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.rk.core.common.bean.JsonMsg;
import org.rk.core.common.constant.RkConst;
import org.rk.core.common.util.RkStrUtil;

/**
 * @author Cavion(曹仁道)
 * @类描述：shiro拦截器
 * 2016年12月11日
 */
public class RKFormAuthenticationFilter extends FormAuthenticationFilter {
	/*
	 *	主要是针对登入成功的处理方法。对于请求头是AJAX的之间返回JSON字符串。
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,	Subject subject, ServletRequest request, ServletResponse response)	throws Exception {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))) {//不是ajax请求
			issueSuccessRedirect(request, response);
		} else {
			httpServletResponse.setCharacterEncoding("UTF-8");
			JsonMsg jMsg=new JsonMsg("登陆成功", JsonMsg.status_200);
			PrintWriter out = httpServletResponse.getWriter();
			out.println(jMsg.toString());
			out.flush();
			out.close();
		}
		return false;
	}

	/**
	 * 主要是处理登入失败的方法
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token,AuthenticationException e, ServletRequest request,ServletResponse response) {
		if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {//不是ajax请求
			setFailureAttribute(request, e);
			return true;
		}
		try {
			JsonMsg jMsg=new JsonMsg("登陆失败", JsonMsg.status_302);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			String message = e.getClass().getSimpleName();
			if ("IncorrectCredentialsException".equals(message)) {
				jMsg.setMsg("密码错误");
			} else if ("UnknownAccountException".equals(message)) {
				jMsg.setMsg("账号不存在");
			} else if ("LockedAccountException".equals(message)) {
				jMsg.setMsg("账号被锁定");
			}else if ("ExcessiveAttemptsException".equals(message)) {
				jMsg.setMsg("用户名或密码错误次数过多,将锁定账号5分钟");
			} else {
				jMsg.setMsg("未知错误");
			}
			out.println(jMsg.toString());
			out.flush();
			out.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return false;
	}

	/**
	 * 所有请求都会经过的方法。
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request,ServletResponse response) throws Exception {
		if (isLoginRequest(request, response)) {
			if (isLoginSubmission(request, response)) {
				if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {//ajax请求
					String vcode = request.getParameter("vcode");
					HttpServletRequest httpservletrequest = (HttpServletRequest) request;
					String vvcode = (String) httpservletrequest.getSession().getAttribute(RkConst.session_key.kaptcha);
					if (!RkStrUtil.hasText(vcode)|| !vvcode.equals(vcode)) {
						JsonMsg jMsg=new JsonMsg("验证码错误", JsonMsg.status_302);
						response.setCharacterEncoding("UTF-8");
						PrintWriter out = response.getWriter();
						out.println(jMsg.toString());
						out.flush();
						out.close();
						return false;
					}
				}
				return executeLogin(request, response);
			} else {
				return true;
			}
		} else {
			if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {//不是ajax请求
				saveRequestAndRedirectToLogin(request, response);
			} else {
				JsonMsg jMsg=new JsonMsg("login", JsonMsg.status_302);
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				out.println(jMsg.toString());
				out.flush();
				out.close();
			}
			return false;
		}
	}
}
